package cn.zhc.controller;


import cn.zhc.bean.Buser;
import cn.zhc.service.BuserService;
import cn.zhc.util.DeCodeUtil;
import cn.zhc.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("buser")
@CrossOrigin
public class BuserController {

    @Autowired
    BuserService buserService;

    @GetMapping("page")
    public Result getPage(Page page, @RequestParam(value = "searchtext", required = false) String searchtext){
        IPage<Buser> result=null;
        if(searchtext==null||searchtext.trim().isEmpty()){
            result=buserService.page(page);
        }else {
            QueryWrapper wrapper=new QueryWrapper();
            wrapper.like("username",searchtext);
            result=buserService.page(page,wrapper);
        }

        return Result.success(result);

    }

    @GetMapping("list")
    public Result getlist(){
        List<Buser> list =buserService.list();
        return Result.success(list);
    }
    @PostMapping("add")
    public Result add(@RequestBody Buser buser){

        buser.setPassword("123123");

        String pass=buser.getPassword();
        String newpass= DeCodeUtil.decode(pass);
        buser.setPassword(newpass);

        buserService.save(buser);
        Buser saveadmin=buserService.getById(buser.getId());
        return Result.success("保存成功",saveadmin);
    }
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Integer id)
    {
        boolean b =buserService.removeById(id);
        if (b){
            return Result.success("删除成功");

        }
        else {
            return Result.fail(201,"删除失败");
        }
    }

    @PutMapping("edit")
    public Result edit(@RequestBody Buser buser)
    {
        buserService.saveOrUpdate(buser);
        boolean b=buserService.saveOrUpdate(buser);
        Buser buser1=buserService.getById(buser.getId());
        if(b){
            return Result.success("保存成功",buser1);
        }
        else{
            return Result.fail(201,"修改失败");
        }
    }


}
